<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>店铺详情页</title>
    <script src="../static/js/jquery.js"></script>
    <script src="../static/js/shop_recommendation.js"></script>
    <script src="../static/js/jquery.cookie.js"></script>
    <script src="../static/layui/layui.js"></script>
    <style>
        /* 朋友圈分享弹窗样式 */
        .share-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        .share-content {
            background-color: white;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        }
        .share-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .share-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        .close-modal {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #999;
        }
        .share-link-section {
            margin-bottom: 10px;
        }
        .link-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }
        .link-container {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        #shopLinkInput {
            flex-grow: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 13px;
            color: #333;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .copy-btn {
            background-color: #6a11cb;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            transition: background-color 0.3s;
        }
        .copy-btn:hover {
            background-color: #5a0dc8;
        }
        /* 基础样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        body {
            background: #f5f7fa;
            color: #333;
            line-height: 1.6;
            min-height: 100vh;
        }

        .container {
            width: 100%;
            height: 100vh;
            background: white;
            position: relative;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        /* 头部样式 */
        .header {
            padding: 20px 40px;
            border-bottom: 1px solid #e0e0e0;
            background: white;
            z-index: 10;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .back-button {
            background: #6c5ce7;
            color: white;
            border: none;
            border-radius: 20px;
            padding: 10px 20px;
            font-size: 14px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 4px 10px rgba(108, 92, 231, 0.3);
            transition: all 0.3s;
        }

        .back-button:hover {
            background: #5241d4;
            transform: translateY(-2px);
        }

        .shop-name {
            font-size: 28px;
            font-weight: bold;
            color: #2d3436;
            position: relative;
            display: inline-block;
        }

        .shop-name::after {
            content: "";
            position: absolute;
            bottom: -5px;
            left: 0;
            width: 100%;
            height: 3px;
            background: linear-gradient(to right, #6c5ce7, #00cec9);
            border-radius: 2px;
        }

        /* 主内容区 */
        .main-content {
            flex: 1;
            padding: 25px 40px;
            overflow: auto;
            background: #f8f9ff;
        }

        .content-wrapper {
            max-width: 1400px;
            margin: 0 auto;
        }

        /* 店铺信息 */
        .shop-info-container {
            display: flex;
            gap: 40px;
            margin-bottom: 40px;
            padding: 30px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
        }

        .shop-details {
            flex: 1;
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .detail-item {
            display: flex;
            align-items: center;
            font-size: 17px;
            padding: 15px;
            border-bottom: 1px dashed #e0e0e0;
        }

        .detail-item:last-child {
            border-bottom: none;
        }

        .shop-image {
            width: 220px;
            height: 220px;
            border-radius: 12px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            position: relative;
            flex-shrink: 0;
        }

        /* 功能按钮区 */
        .action-buttons {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 20px;
            margin-bottom: 40px;
            padding: 30px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
        }

        .action-button {
            background: linear-gradient(135deg, #f6f9ff 0%, #e9f0ff 100%);
            border: 1px solid #dbe6ff;
            border-radius: 12px;
            padding: 20px 15px;
            display: flex;
            flex-direction: column;
            align-items: center;
            cursor: pointer;
            transition: all 0.3s;
            text-align: center;
        }

        .action-button:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
        }

        .icon {
            width: 28px;
            height: 28px;
            margin-bottom: 12px;
        }

        /* 评论区 */
        .comments-section {
            padding: 30px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
            margin-top: 20px;
        }

        .section-title {
            font-size: 22px;
            font-weight: bold;
            margin-bottom: 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #2d3436;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .add-comment {
            background: linear-gradient(to right, #6c5ce7, #00cec9);
            color: white;
            border: none;
            border-radius: 20px;
            padding: 10px 20px;
            font-size: 14px;
            cursor: pointer;
            box-shadow: 0 4px 10px rgba(108, 92, 231, 0.3);
            transition: all 0.3s;
        }

        .comments-container {
            display: flex;
            gap: 25px;
            margin-top: 20px;
        }

        /* 评论和打卡分区样式 */
        .comments-column, .checkins-column {
            flex: 1;
        }

        .column-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid #f0f0f0;
        }

        .comments-list, .checkins-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        /* 评论项样式 */
        .comment-item {
            background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            border-left: 4px solid #6c5ce7;
            transition: all 0.3s;
        }

        .checkin-item {
            background: linear-gradient(135deg, #fff8e1 0%, #fff3cd 100%);
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            border-left: 4px solid #fdcb6e;
            transition: all 0.3s;
        }

        .comment-item:hover, .checkin-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(108, 92, 231, 0.1);
        }

        .comment-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px dashed #e0e0e0;
        }

        .comment-header img {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid white;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .comment-header div {
            margin-left: 12px;
        }

        .comment-header div:first-child {
            font-weight: 600;
            color: #2d3436;
            font-size: 16px;
        }

        .comment-header div:last-child {
            font-size: 12px;
            color: #999;
            margin-top: 3px;
        }

        .comment-content {
            font-size: 15px;
            line-height: 1.8;
            color: #4a4a4a;
            padding: 5px 0 15px;
        }

        /* 评论操作区 */
        .comment-actions {
            margin-top: 15px;
            display: flex;
            align-items: center;
            gap: 15px;
            font-size: 14px;
            color: #666;
        }

        .comment-actions button {
            background: none;
            border: none;
            color: inherit;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 5px;
            transition: color 0.2s;
        }

        .comment-actions button:hover {
            color: #6c5ce7;
        }

        /* 点赞高亮样式 */
        .like-btn.liked {
            color: #ff4d4f;
            font-weight: bold;
            animation: pulse 0.5s ease;
        }

        .like-btn.liked i {
            text-shadow: 0 0 10px rgba(255, 77, 79, 0.5);
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.2); }
            100% { transform: scale(1); }
        }

        /* 回复相关 */
        .reply-input-container {
            margin-top: 10px;
            display: none;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 8px;
        }

        .reply-input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: none;
            margin-bottom: 5px;
        }

        .reply-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .reply-btn {
            padding: 4px 10px;
            background: #6c5ce7;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .cancel-reply-btn {
            padding: 4px 10px;
            background: #eee;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .child-comments {
            margin-left: 30px;
            padding-left: 15px;
            border-left: 2px solid #eee;
            margin-top: 10px;
        }

        .reply-item {
            padding: 12px 0;
            border-bottom: 1px dashed #eee;
        }

        .reply-item:last-child {
            border-bottom: none;
        }

        .reply-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            font-size: 13px;
        }

        .reply-author {
            font-weight: 600;
            color: #2d3436;
        }

        .reply-time {
            color: #999;
        }

        .reply-content {
            font-size: 14px;
            color: #4a4a4a;
            margin-bottom: 8px;
        }

        /* 轮播图 */
        .carousel-wrapper {
            width: 100%;
            height: 100%;
            overflow: hidden;
            position: relative;
        }

        .carousel-list {
            display: flex;
            height: 100%;
            transition: transform 0.5s ease;
        }

        .carousel-list img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            flex-shrink: 0;
        }

        .carousel-btn {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(0,0,0,0.3);
            color: white;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
        }

        .prev-btn { left: 10px; }
        .next-btn { right: 10px; }

        .carousel-indicators {
            position: absolute;
            bottom: 10px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            gap: 8px;
        }

        .carousel-indicators span {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #ddd;
            cursor: pointer;
        }

        .carousel-indicators span.active {
            background: #6c5ce7;
        }

        /* 弹窗样式 */
        .collection-dialog, .checkin-dialog, .rating-dialog, .share-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100vh;
            background: rgba(0,0,0,0.5);
            z-index: 9999;
        }

        .dialog-content, .checkin-dialog-content, .rating-dialog-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 400px;
        }

        .share-content {
            margin: auto;
            background: white;
            border-radius: 16px 16px 0 0;
            padding: 20px;
            width: 100%;
        }

        /* 响应式优化 */
        @media (max-width: 1200px) {
            .action-buttons { grid-template-columns: repeat(3, 1fr); }
            .shop-details { grid-template-columns: 1fr; }
        }

        @media (max-width: 992px) {
            .header { padding: 15px 20px; }
            .main-content { padding: 15px 20px; }
            .shop-info-container { flex-direction: column; padding: 20px; }
            .shop-image { width: 100%; height: 250px; margin-top: 20px; }
            .action-buttons { grid-template-columns: repeat(2, 1fr); padding: 20px; }
            .comments-container { flex-direction: column; } /* 小屏幕下评论和打卡垂直排列 */
        }

        @media (max-width: 768px) {
            .shop-name { font-size: 22px; }
            .action-buttons { grid-template-columns: 1fr; }
        }
        .comment-item {
            margin: 15px 0;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }

        .replies-container {
            /* 回复区域缩进，区分主评论 */
            padding-left: 20px;
            margin-top: 10px;
        }

        .reply-item {
            /* 回复项样式，与主评论区分 */
            font-size: 14px;
            color: #555;
            background: #f9f9f9;
            margin: 8px 0;
            padding: 8px;
            border-radius: 4px;
        }

        .no-replies {
            /* 暂无回复样式，与回复项保持一致 */
            font-size: 14px;
            color: #999;
            padding: 8px;
            margin: 8px 0;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1 class="shop-name" id="shop-name" th:text="${shop.name}"></h1>
        <button class="back-button" onclick="goBack()">
            <svg viewBox="0 0 24 24">
                <path fill="currentColor" d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
            </svg>
            返回
        </button>
    </div>

    <div class="main-content">
        <div class="content-wrapper">
            <div class="shop-info-container">
                <div class="shop-details">
                    <div class="detail-item">
                        <svg class="icon" viewBox="0 0 24 24" width="22" height="22" style="margin-right: 10px; color: #ffc107;">
                            <path fill="currentColor" d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
                        </svg>
                        <span>评分:
                            <span id="ratingStars" class="rating"></span>
                            <span id="ratingInfo" th:text="'- 加载中...'"></span>
                        </span>
                    </div>
                    <div class="detail-item">
                        <svg class="icon" viewBox="0 0 24 24" width="22" height="22" style="margin-right: 10px; color: #00cec9;">
                            <path fill="currentColor" d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/>
                        </svg>
                        <span>营业时间: </span>
                        <span th:text="${#dates.format(shop.openTime, 'HH:mm')} + '-' + ${#dates.format(shop.closeTime, 'HH:mm')}"></span>
                    </div>

                    <div class="detail-item">
                        <svg class="icon" viewBox="0 0 24 24" width="22" height="22" style="margin-right: 10px; color: #ff7675;">
                            <path fill="currentColor" d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5a2.5 2.5 0 0 1 0-5 2.5 2.5 0 0 1 0 5z"/>
                        </svg>
                        <span>地址: </span>
                        <span id="locationText"></span>
                    </div>
                    <div class="detail-item">
                        <svg class="icon" viewBox="0 0 24 24" width="22" height="22" style="margin-right: 10px; color: #00b894;">
                            <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 15h-2v-6h2v6zm4 0h-2v-6h2v6zm.5-12h-7c-.83 0-1.5.67-1.5 1.5v7c0 .83.67 1.5 1.5 1.5h7c.83 0 1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5z"/>
                        </svg>
                        <span>店铺状态:
                            <span id="shopStatusText">加载中...</span>
                        </span>
                    </div>

                    <input type="hidden" id="shopOpenTime" th:value="${#dates.format(shop.openTime, 'HH:mm:ss')}">
                    <input type="hidden" id="shopCloseTime" th:value="${#dates.format(shop.closeTime, 'HH:mm:ss')}">

                    <div class="detail-item">
                        <svg class="icon" viewBox="0 0 24 24" width="22" height="22" style="margin-right: 10px; color: #6c5ce7;">
                            <path fill="currentColor" d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 9h-2V5h2v6zm0 4h-2v-2h2v2z"/>
                        </svg>
                        <span>店铺描述: </span>
                        <span th:text="${shop.desc}"></span>
                    </div>

                    <div class="shop-image shop-carousel">
                        <div class="carousel-wrapper" id="carouselWrapper">
                            <div class="carousel-list" id="carouselList"></div>
                        </div>
                        <button class="carousel-btn prev-btn" id="prevBtn">←</button>
                        <button class="carousel-btn next-btn" id="nextBtn">→</button>
                        <div class="carousel-indicators" id="carouselIndicators"></div>
                    </div>
                </div>
            </div>

            <div class="action-buttons">
                <div class="action-button" id="likeButton">
                    <svg class="icon" viewBox="0 0 24 24" style="color: #ff7675;">
                        <path fill="currentColor" d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                    </svg>
                    <span id="likeText">点赞</span>
                    <span id="likeCount" style="font-size: 12px; margin-top: 4px; color: #999;">0</span>
                </div>

                <div class="action-button" onclick="showCollectionDialog()">
                    <svg class="icon" viewBox="0 0 24 24" style="color: #fdcb6e;">
                        <path fill="currentColor" d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"/>
                    </svg>
                    <span>收藏</span>
                </div>

                <div class="action-button" id="ratingButton">
                    <svg class="icon" viewBox="0 0 24 24" style="color: #00cec9;">
                        <path fill="currentColor" d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
                    </svg>
                    <span>评分</span>
                </div>

                <div class="action-button" id="checkinButton">
                    <svg class="icon" viewBox="0 0 24 24" style="color: #74b9ff;">
                        <path fill="currentColor" d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/>
                    </svg>
                    <span>打卡</span>
                </div>

                <div class="action-button" onclick="openShareModal()">
                    <svg class="icon" viewBox="0 0 24 24" style="color: #ffeaa7;">
                        <path fill="currentColor" d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/>
                    </svg>
                    <span>分享给朋友</span>
                </div>
            </div>

            <div class="comments-section">
                <div class="section-title">
                    <h3>用户反馈</h3>
                    <button class="add-comment">写评价</button>
                </div>
                <div class="comments-container">
                    <!-- 左侧：用户评价 -->
                    <div class="comments-column">
                        <h4 class="column-title">用户评价</h4>
                        <div class="comments-list" id="commentsList">
                            <!-- 评论内容将通过JS动态生成 -->
                        </div>
                        <div style="text-align: center; margin: 20px 0;">
                            <button id="loadMoreComments" style="padding: 8px 16px; background: #6c5ce7; color: white; border: none; border-radius: 4px; cursor: pointer;">
                                加载更多评论
                            </button>
                        </div>
                    </div>

                    <!-- 右侧：打卡记录 -->
                    <div class="checkins-column">
                        <h4 class="column-title">打卡记录</h4>
                        <div class="checkins-list" id="checkinsList">
                            <!-- 打卡内容将通过JS动态生成 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 收藏弹框 -->
    <div class="collection-dialog" id="collectionDialog">
        <div class="dialog-mask"></div>
        <div class="dialog-content">
            <h3>收藏设置</h3>
            <div style="margin: 15px 0;">
                <label>收藏理由</label>
                <textarea id="reasonInput" rows="3" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" placeholder="请输入收藏理由..."></textarea>
            </div>
            <div style="margin: 15px 0;">
                <label>选择收藏文件夹 <span style="color: red;">*</span></label>
                <div id="folderSelectContainer" style="display: flex; gap: 8px; flex-wrap: wrap; align-items: center;">
                    <select id="folderSelect" class="folder-select" data-level="1" style="padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; min-width: 120px;">
                        <option value="0">默认文件夹</option>
                    </select>
                </div>
                <input type="hidden" id="selectedFolderId" value="0">
                <button id="createFolderBtn" style="margin-top: 8px; padding: 4px 8px; font-size: 12px; color: #fdcb6e; background: transparent; border: none; cursor: pointer;">
                    + 新建文件夹
                </button>
                <div id="newFolderInputContainer" style="margin-top: 8px; display: none;">
                    <input type="text" id="newFolderName" placeholder="输入文件夹名称" style="padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; width: 200px; margin-right: 8px;">
                    <button id="confirmCreateFolder" style="padding: 6px 10px; background: #fdcb6e; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;">确认创建</button>
                    <button id="cancelCreateFolder" style="padding: 6px 10px; background: #eee; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;">取消</button>
                </div>
            </div>
            <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                <button id="cancelBtn" style="padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;">取消</button>
                <button id="confirmBtn" style="padding: 6px 12px; background: #fdcb6e; border: none; border-radius: 4px; cursor: pointer;">确认收藏</button>
            </div>
        </div>
    </div>

    <!-- 打卡弹框 -->
    <div class="checkin-dialog" id="checkinDialog">
        <div class="checkin-dialog-content">
            <h3 style="margin-top: 0; margin-bottom: 20px; font-size: 18px; color: #2d3436; text-align: center;">店铺打卡</h3>
            <div style="margin-bottom: 25px;">
                <label style="display: block; margin-bottom: 8px; font-size: 14px; color: #666;">打卡备注（可选）</label>
                <textarea id="checkinContext" rows="4" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; resize: none;" placeholder="分享你的打卡心情..."></textarea>
            </div>
            <div style="margin: 15px 0;">
                <label style="display: block; margin-bottom: 8px;">上传打卡图片（可选）</label>
                <input type="file" id="checkinFileInput" accept="image/*" style="display: none;">
                <button id="checkinSelectImageBtn" style="padding: 6px 12px; background: #eee; border: none; border-radius: 4px; cursor: pointer;">
                    选择图片
                </button>
                <div id="checkinImagePreviewContainer" style="margin-top: 10px; display: none;">
                    <img id="checkinImagePreview" src="" alt="打卡图片预览" style="max-width: 200px; max-height: 200px; border-radius: 8px;">
                    <button id="checkinRemoveImageBtn" style="margin-left: 10px; color: #ff4d4f; background: transparent; border: none; cursor: pointer;">
                        移除
                    </button>
                </div>
            </div>
            <div style="display: flex; justify-content: center; gap: 20px;">
                <button id="checkinCancelBtn" style="padding: 10px 25px; border: 1px solid #ddd; border-radius: 20px; background: white; cursor: pointer;">取消</button>
                <button id="checkinConfirmBtn" style="padding: 10px 25px; border: none; border-radius: 20px; background: linear-gradient(135deg, #74b9ff, #0984e3); color: white; cursor: pointer;">确认打卡</button>
            </div>
        </div>
    </div>

    <!-- 评分弹框 -->
    <div class="rating-dialog" id="ratingDialog">
        <div class="rating-dialog-content">
            <h3 style="margin-top: 0; margin-bottom: 20px; font-size: 18px; color: #2d3436; text-align: center;">给店铺评分</h3>
            <div class="star-selection" style="display: flex; justify-content: center; gap: 15px; margin-bottom: 25px;">
                <span class="rating-star-option" data-star="1" style="font-size: 40px; color: #ddd; cursor: pointer;">★</span>
                <span class="rating-star-option" data-star="2" style="font-size: 40px; color: #ddd; cursor: pointer;">★</span>
                <span class="rating-star-option" data-star="3" style="font-size: 40px; color: #ddd; cursor: pointer;">★</span>
                <span class="rating-star-option" data-star="4" style="font-size: 40px; color: #ddd; cursor: pointer;">★</span>
                <span class="rating-star-option" data-star="5" style="font-size: 40px; color: #ddd; cursor: pointer;">★</span>
            </div>
            <input type="hidden" id="selectedStar" value="0">
            <div class="rating-tip" style="text-align: center; color: #666; font-size: 14px; margin-bottom: 25px;">
                请选择1-5星评分，星星点亮代表选中
            </div>
            <div style="display: flex; justify-content: center; gap: 20px;">
                <button id="cancelRatingBtn" style="padding: 10px 25px; border: 1px solid #ddd; border-radius: 20px; background: white; cursor: pointer;">取消</button>
                <button id="confirmRatingBtn" style="padding: 10px 25px; border: none; border-radius: 20px; background: linear-gradient(135deg, #6c5ce7, #00cec9); color: white; cursor: pointer;">提交评分</button>
            </div>
        </div>
    </div>

    <!-- 分享弹窗（朋友圈专用，仅复制链接） -->
    <div class="share-modal" id="shareModal">
        <div class="share-content">
            <div class="share-header">
                <h3 class="share-title">分享店铺链接</h3>
                <button class="close-modal" onclick="closeShareModal()">&times;</button>
            </div>
            <!-- 链接复制区域 -->
            <div class="share-link-section">
                <div class="link-label">店铺链接</div>
                <div class="link-container">
                    <input type="text" id="shopLinkInput" value="" readonly>
                    <button class="copy-btn" onclick="copyShopLink()">复制链接</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script th:inline="javascript">
    let currentShopId = [[${shopId}]];
    let shopId = [[${shopId}]];
    let currentUserId = null;
    let user = null;
    let ratingTotal=0;
    let ratingAvg= "0.0";
    let checkinImgSrc = "";
    const bannerUrlsStr = [[${shop.bannerUrls}]];
    let currentIndex = 0;
    let bannerUrls = [];
    let  shoplatitude=[[${shop.latitude}]];
    let  shoplongitude=[[${shop.longitude}]];
    let checkinList = [];
    let totalLikes = 0;
    let totalReviews = 0;
    let checkId=null;
    let currentPage = 1;
    const pageSize = 5;
    let isLoading = false;
    let likedCheckinIds = new Set();
    let likedCommentIds = new Set();
    let currentCommentPage = 1;
    const commentPageSize = 5;
    let hasMoreComments = true;
    $(function () {
        window.goBack = function() {
            if (window.history.length > 1) {
                window.history.back();
            } else {
                window.location.href = "/iframeClient";
            }
        };

        $.ajax({
            url: "/user/getCurrentUser",
            type: "post",
            success: function (res) {
                user = res.data;
                currentUserId = user.id;
                console.log("currentUserId"+currentUserId)
                getLikeStatusAndCount();
                loadFolders(currentUserId);
            },
            error: function () {
                alert("获取用户信息失败，请重新登录");
            }
        });

        try {
            bannerUrls = JSON.parse(String(bannerUrlsStr));
            initCarousel();
        } catch (e) {
            console.error("解析失败：", e);
        }

        document.getElementById('cancelBtn').addEventListener('click', closeCollectionDialog);
        document.getElementById('confirmBtn').addEventListener('click', handleConfirmCollection);
        document.getElementById('createFolderBtn').addEventListener('click', showNewFolderInput);
        document.getElementById('cancelCreateFolder').addEventListener('click', hideNewFolderInput);
        document.getElementById('confirmCreateFolder').addEventListener('click', createNewFolder);

        // 打卡功能
        document.getElementById('checkinButton').addEventListener('click', function() {
            if (!currentUserId) {
                alert('请先登录后再打卡～');
                return;
            }
            document.getElementById('checkinContext').value = '';
            document.getElementById('checkinFileInput').value = '';
            document.getElementById('checkinImagePreviewContainer').style.display = 'none';
            checkinImgSrc = "";
            document.getElementById('checkinDialog').style.display = 'block';
        });

        document.getElementById('checkinSelectImageBtn').addEventListener('click', function() {
            document.getElementById('checkinFileInput').click();
        });

        document.getElementById('checkinFileInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const previewContainer = document.getElementById('checkinImagePreviewContainer');
                const previewImg = document.getElementById('checkinImagePreview');
                const reader = new FileReader();
                reader.onload = function(event) {
                    previewImg.src = event.target.result;
                    previewContainer.style.display = 'flex';
                };
                reader.readAsDataURL(file);
            }
        });

        document.getElementById('checkinRemoveImageBtn').addEventListener('click', function() {
            document.getElementById('checkinImagePreviewContainer').style.display = 'none';
            document.getElementById('checkinFileInput').value = '';
            checkinImgSrc = "";
        });

        document.getElementById('checkinCancelBtn').addEventListener('click', function() {
            document.getElementById('checkinDialog').style.display = 'none';
        });

        document.getElementById('checkinDialog').addEventListener('click', function(e) {
            if (e.target === document.getElementById('checkinDialog')) {
                document.getElementById('checkinDialog').style.display = 'none';
            }
        });

        document.getElementById('checkinConfirmBtn').addEventListener('click', function() {
            const checkinContext = document.getElementById('checkinContext').value.trim();
            const file = document.getElementById('checkinFileInput').files[0];

            if (file) {
                checkinUploadImage(file, function(imgSrc) {
                    checkinSubmitData(checkinContext, imgSrc);
                });
            } else {
                checkinSubmitData(checkinContext, "");
            }
        });

        // 评分功能
        const ratingDialog = document.getElementById('ratingDialog');
        const ratingButton = document.getElementById('ratingButton');
        const cancelRatingBtn = document.getElementById('cancelRatingBtn');
        const confirmRatingBtn = document.getElementById('confirmRatingBtn');
        const starOptions = document.querySelectorAll('.rating-star-option');
        const selectedStarInput = document.getElementById('selectedStar');

        ratingButton.addEventListener('click', function () {
            if (!currentUserId) {
                alert('请先登录后再评分～');
                return;
            }
            $.ajax({
                url: "/shop/ratingCount",
                type: "post",
                data: { userId: currentUserId, shopId: currentShopId },
                success: function (res) {
                    if (res.code === 200) {
                        if (res.data >0) {
                            alert('您已经评分过了');
                            return;
                        }else {
                            starOptions.forEach(star => {
                                star.style.color = '#ddd';
                            });
                            selectedStarInput.value = '0';
                            ratingDialog.style.display = 'block';
                        }
                    } else {
                        alert('查询评分状态失败：' + res.msg);
                    }
                },
                error: function () {
                    alert('查询评分状态出错，请重试');
                }
            });
        });

        cancelRatingBtn.addEventListener('click', function () {
            ratingDialog.style.display = 'none';
        });

        starOptions.forEach(star => {
            star.addEventListener('click', function () {
                const selectedStar = this.getAttribute('data-star');
                selectedStarInput.value = selectedStar;
                starOptions.forEach(s => {
                    const sStar = s.getAttribute('data-star');
                    s.style.color = sStar <= selectedStar ? '#ffc107' : '#ddd';
                });
            });
        });

        confirmRatingBtn.addEventListener('click', function () {
            const selectedStar = selectedStarInput.value;
            const rating = parseInt(selectedStar, 10);
            if (isNaN(rating) || rating < 1 || rating > 5) {
                alert('请选择1-5星之间的评分～');
                return;
            }
            $.ajax({
                url: "/shop/rating",
                type: "post",
                data: {
                    rating: rating,
                    shopId: currentShopId,
                    userId: currentUserId
                },
                success: function (res) {
                    if (res.code === 200) {
                        alert(`评分成功！您给了${rating}星`);
                        ratingDialog.style.display = 'none';
                        fetchRatingData();
                    } else {
                        alert("评分失败：" + res.msg);
                    }
                },
                error: function (res) {
                    alert("评分出错：" + res.responseText);
                }
            });
        });

        ratingDialog.addEventListener('click', function (e) {
            if (e.target === ratingDialog) {
                ratingDialog.style.display = 'none';
            }
        });

        updateShopStatus();
        setInterval(updateShopStatus, 60000);
        updateRatingUI();
        fetchRatingData();
        //getReviewsByShopId();
        getCheckinsByShopId();

        getAddressFromKnownCoordinates(shoplongitude, shoplatitude)
            .then(addressInfo => {
                $("#locationText").html(addressInfo.province + " " + addressInfo.city + " " + addressInfo.district)
            })

        document.querySelector(".add-comment").addEventListener("click", function () {
            if (!currentUserId) {
                alert("请先登录后再发表评论～");
                return;
            }
            showAddCommentDialog();
        });


        getReviewsByShopId(currentCommentPage, commentPageSize);

        // 加载更多评论按钮点击事件
        document.getElementById('loadMoreComments').addEventListener('click', function() {
            if (isLoading || !hasMoreComments) return;
            currentCommentPage++; // 页码+1
            getReviewsByShopId(currentCommentPage, commentPageSize, true); // 加载下一页并追加
        });



        // 复制链接并提示
        window.copyShopLink = function() {
            const linkInput = document.getElementById('shopLinkInput');
            linkInput.select(); // 选中链接
            document.execCommand('copy'); // 执行复制
            // 复制成功提示（2秒后恢复）
            const copyBtn = document.querySelector('.copy-btn');
            const originalText = copyBtn.textContent;
            copyBtn.textContent = '已复制!';
            setTimeout(() => {
                copyBtn.textContent = originalText;
            }, 2000);
        };
        // 关闭分享弹窗
        window.closeShareModal = function() {
            document.getElementById('shareModal').style.display = 'none';
        };
        // 打开分享弹窗（接收动态的店铺ID）
        window.openShareModal = function() {
            const shopLink = `http://localhost:8081/homepage/goToDetail?id=${shopId}`;
            document.getElementById('shopLinkInput').value = shopLink;
            // 显示弹窗
            document.getElementById('shareModal').style.display = 'flex';
        };
        // 绑定分享按钮点击事件（触发弹窗）

        $('#momentsList').on('click', '.share-btn', function() {
            // 获取当前动态的店铺ID
            //const shopId = $(this).closest('.moment-item').find('.fa-map-marker').parent().data('shop-id');
            // 打开分享弹窗
            openShareModal(shopId);
        });

    });
    // 修改评论加载函数，支持分页和追加模式
    function getReviewsByShopId(page, pageSize, isAppend = false) {
        if (isLoading) return;
        isLoading = true;

        // 显示加载中状态（首次加载或追加时）
        const commentsList = document.getElementById('commentsList');
        const loadMoreBtn = document.getElementById('loadMoreComments');

        if (!isAppend) {
            commentsList.innerHTML = '<div style="text-align: center; padding: 20px;"><i class="layui-icon layui-icon-loading layui-icon-loading-1"></i> 加载评论中...</div>';
        } else {
            loadMoreBtn.innerHTML = '<i class="layui-icon layui-icon-loading layui-icon-loading-1"></i> 加载中...';
        }

        $.ajax({
            url: "/shop/getShopReviews",
            type: "post",
            data: {
                shopId: currentShopId,
                page: page,       // 传递页码
                pageSize: pageSize // 传递每页条数
            },
            success: function (res) {
                console.log(res)
                console.log("getShopReviews"+res)
                console.log("getShopReviews"+res.data.total)
                if (res.code === 200) {
                    const reviews = res.data.rows|| [];
                    const total = res.data.total || 0;

                    // 判断是否还有更多评论
                    hasMoreComments = (page * pageSize) < total;

                    if (!isAppend && reviews.length === 0) {
                        // 首次加载且无数据
                        commentsList.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;">暂无评论</div>';
                        loadMoreBtn.style.display = 'none';
                        return;
                    }

                    // 渲染评论（首次加载清空，追加模式保留原有内容）
                    if (!isAppend) {
                        commentsList.innerHTML = '';
                    }
                    reviews.forEach(review => {
                        const reviewHtml = `
                        <div class="comment-item" data-review-id="${review.id}">
                            <div class="comment-header">
                                <img src="${review.user.icon || ''}" alt="用户头像">
                                <div>
                                    <div>${review.user.username}</div>
                                    <div>${formatTime(review.createdAt)}</div>
                                </div>
                            </div>
                            <div class="comment-content">${review.content}</div>

                            <!-- 评论图片（如果有） -->
                            ${review.imageUrls ? `
                                <div class="comment-images" style="margin: 10px 0;">
                                    <img src="${review.imageUrls}" style="max-width: 200px; max-height: 200px; border-radius: 4px;"
                                         onclick="previewImage('${review.imageUrls}')">
                                </div>
                            ` : ''}

                            <div class="comment-actions">
                                <button class="like-btn" onclick="likeComment(${review.id})">
                                    <i class="fas fa-heart"></i> 点赞量 ${review.likeCount || 0}
                                </button>
                                <button class="reply-btn" onclick="showReplyInput(${review.id})">
                                    <i class="fas fa-reply"></i> 回复
                                </button>
                                <button class="view-replies-btn" onclick="toggleReplies(${review.id})">
                                    <i class="fas fa-comment-dots"></i> 查看回复 (${review.replyCount || 0})
                                </button>
                            </div>

                            <div class="reply-input-container" id="replyContainer-${review.id}" style="display: none; margin-top: 10px; padding: 10px; background: #f5f5f5; border-radius: 4px;">
                                <textarea id="replyInput-${review.id}" rows="2" placeholder="写下你的回复..."></textarea>
                                <div style="margin-top: 8px; text-align: right;">
                                    <button class="cancel-reply-btn" onclick="hideReplyInput(${review.id})">取消</button>
                                    <button class="submit-reply-btn" onclick="submitReply(${review.id})">回复</button>
                                </div>
                            </div>
                            <div class="child-comments" id="repliesContainer-${review.id}" style="display: none;">
                                <div class="loading-replies">加载中...</div>
                            </div>
                        </div>
                    `;
                        commentsList.innerHTML += reviewHtml;
                    });

                    // 控制加载更多按钮显示
                    if (hasMoreComments) {
                        loadMoreBtn.style.display = 'block';
                        loadMoreBtn.innerHTML = '加载更多评论';
                    } else {
                        loadMoreBtn.style.display = 'none';
                        // 追加"没有更多"提示（仅在有数据时）
                        if (total > 0) {
                            commentsList.innerHTML += '<div style="text-align: center; padding: 15px; color: #999;">已显示全部评论</div>';
                        }
                    }
                } else {
                    if (!isAppend) {
                        commentsList.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;">加载评论失败</div>';
                    } else {
                        alert('加载更多评论失败');
                        loadMoreBtn.innerHTML = '加载更多评论';
                    }
                }
            },
            error: function() {
                if (!isAppend) {
                    commentsList.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;">加载评论失败</div>';
                } else {
                    alert('网络错误，加载更多评论失败');
                    loadMoreBtn.innerHTML = '加载更多评论';
                }
            },
            complete: function() {
                isLoading = false; // 结束加载状态
            }
        });
    }
    let currentCheckinPage = 1; // 当前页码
    const checkinPageSize = 5; // 每页显示数量
    let allCheckins = []; // 缓存所有打卡记录
    let totalCheckins = 0; // 总记录数
    let hasMoreCheckins = true; // 是否还有更多数据
    let isLoadingCheckins = false; // 加载状态锁

    // 修改为前端分页+加载更多模式的打卡记录函数
    function getCheckinsByShopId() {
        if (isLoadingCheckins) return;
        isLoadingCheckins = true;

        const checkinsList = document.getElementById('checkinsList');

        // 首次加载显示加载中
        if (currentCheckinPage === 1) {
            checkinsList.innerHTML = '<div style="text-align: center; padding: 20px;"><i class="layui-icon layui-icon-loading layui-icon-loading-1"></i> 加载打卡记录中...</div>';
        } else {
            // 加载更多时显示底部加载提示（与评论区样式一致）
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'checkin-loading';
            loadingDiv.style.textAlign = 'center';
            loadingDiv.style.padding = '10px';
            loadingDiv.innerHTML = '<i class="layui-icon layui-icon-loading layui-icon-loading-1"></i> 加载中...';
            checkinsList.appendChild(loadingDiv);
        }

        $.ajax({
            url: "/checkings/getCheckinsByUserId",
            type: "post",
            data: {
                Uid: null,
                shopId: currentShopId
                // 不传递page参数，后端返回所有数据
            },
            success: function (res) {
                // 移除加载提示
                const loadingEl = document.querySelector('.checkin-loading');
                if (loadingEl) loadingEl.remove();

                if (res.code === 200) {
                    // 缓存所有打卡记录
                    allCheckins = res.data || [];
                    totalCheckins = allCheckins.length;

                    // 计算是否还有更多数据
                    hasMoreCheckins = (currentCheckinPage * checkinPageSize) < totalCheckins;

                    // 首次加载且无数据
                    if (currentCheckinPage === 1 && totalCheckins === 0) {
                        checkinsList.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;">暂无打卡记录</div>';
                        return;
                    }

                    // 首次加载时清空列表，后续加载追加内容（与评论区逻辑一致）
                    if (currentCheckinPage === 1) {
                        checkinsList.innerHTML = '';
                    }

                    // 截取当前页数据
                    const startIndex = (currentCheckinPage - 1) * checkinPageSize;
                    const endIndex = startIndex + checkinPageSize;
                    const currentPageCheckins = allCheckins.slice(startIndex, endIndex);

                    // 渲染当前页打卡记录
                    currentPageCheckins.forEach(checkin => {
                        const checkinHtml = `
                        <div class="checkin-item" data-review-id="${checkin.id}">
                            <div class="comment-header">
                                <img src="${checkin.user.icon || ''}" alt="用户头像">
                                <div>
                                    <div>${checkin.user.username}</div>
                                    <div>${formatTime(checkin.createdAt)}</div>
                                </div>
                            </div>
                            <div class="comment-content">${checkin.context}</div>
                            <div class="comment-actions">
                                <button class="like-btn" onclick="likeComment(${checkin.id})">
                                    <i class="fas fa-heart"></i> 点赞量${checkin.likes || 0}
                                </button>
                                ${checkin.reviews > 0 ? `
                                <button class="view-replies-btn" onclick="toggleReplies(${checkin.id})">
                                    <i class="fas fa-comment-dots"></i> 查看回复 (${checkin.reviews})
                                </button>
                                ` : ''}
                            </div>
                            <div class="reply-input-container" id="replyContainer-${checkin.id}" style="display: none;">
                                <textarea class="reply-input" id="replyInput-${checkin.id}" rows="2" placeholder="写下你的回复..."></textarea>
                                <div class="reply-actions">
                                    <button class="cancel-reply-btn" onclick="hideReplyInput(${checkin.id})">取消</button>
                                    <button class="reply-btn" onclick="submitReply(${checkin.id})">回复</button>
                                </div>
                            </div>
                            <div class="child-comments" id="repliesContainer-${checkin.id}" style="display: none;">
                                <div class="loading-replies">加载回复中...</div>
                            </div>
                        </div>
                    `;
                        checkinsList.innerHTML += checkinHtml;
                    });

                    // 处理加载更多按钮（与评论区样式、逻辑完全一致）
                    const loadMoreBtnId = 'loadMoreCheckins';
                    let loadMoreBtn = document.getElementById(loadMoreBtnId);

                    // 移除已有按钮（避免重复）
                    if (loadMoreBtn) {
                        loadMoreBtn.remove();
                    }

                    // 有更多数据时显示加载更多按钮
                    if (hasMoreCheckins) {
                        loadMoreBtn = document.createElement('button');
                        loadMoreBtn.id = loadMoreBtnId;
                        // 与评论区加载更多按钮样式完全一致
                        loadMoreBtn.style = `
                        padding: 8px 16px;
                        background: #6c5ce7;
                        color: white;
                        border: none;
                        border-radius: 4px;
                        cursor: pointer;
                        margin: 20px auto;
                        display: block;
                    `;
                        loadMoreBtn.textContent = '加载更多打卡记录';
                        loadMoreBtn.onclick = function() {
                            currentCheckinPage++; // 页码+1
                            getCheckinsByShopId(); // 加载下一页
                        };
                        checkinsList.parentNode.appendChild(loadMoreBtn);
                    } else if (totalCheckins > 0) {
                        // 没有更多数据时显示提示（与评论区一致）
                        const endTip = document.createElement('div');
                        endTip.style.textAlign = 'center';
                        endTip.style.padding = '15px';
                        endTip.style.color = '#999';
                        endTip.textContent = '已显示全部打卡记录';
                        checkinsList.appendChild(endTip);
                    }
                } else {
                    if (currentCheckinPage === 1) {
                        checkinsList.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;">加载打卡记录失败</div>';
                    } else {
                        alert('加载更多打卡记录失败：' + (res.msg || '未知错误'));
                    }
                }
            },
            error: function() {
                // 移除加载提示
                const loadingEl = document.querySelector('.checkin-loading');
                if (loadingEl) loadingEl.remove();

                if (currentCheckinPage === 1) {
                    checkinsList.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;">加载打卡记录失败</div>';
                } else {
                    alert('网络错误，加载更多打卡记录失败');
                }
            },
            complete: function() {
                isLoadingCheckins = false; // 释放加载锁
            }
        });
    }


    // 渲染指定页的打卡记录
    function renderCheckinPage(page) {
        const checkinsList = document.getElementById('checkinsList');
        currentCheckinPage = page;

        // 计算当前页数据的起始和结束索引
        const startIndex = (page - 1) * checkinPageSize;
        const endIndex = startIndex + checkinPageSize;
        const currentPageCheckins = allCheckins.slice(startIndex, endIndex); // 截取当前页数据
        const hasMore = endIndex < totalCheckins; // 是否还有更多数据

        // 清空列表（重新渲染当前页）
        checkinsList.innerHTML = '';

        // 无数据时显示提示
        if (totalCheckins === 0) {
            checkinsList.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;">暂无打卡记录</div>';
            return;
        }

        // 渲染当前页打卡记录
        currentPageCheckins.forEach(checkin => {
            const checkinHtml = `
            <div class="checkin-item" data-review-id="${checkin.id}">
                <div class="comment-header">
                    <img src="${checkin.user.icon || ''}" alt="用户头像">
                    <div>
                        <div>${checkin.user.username}</div>
                        <div>${formatTime(checkin.createdAt)}</div>
                    </div>
                </div>
                <div class="comment-content">${checkin.context}</div>
                <div class="comment-actions">
                    <button class="like-btn" onclick="likeComment(${checkin.id})">
                        <i class="fas fa-heart"></i> 点赞量${checkin.likes || 0}
                    </button>
                    ${checkin.reviews > 0 ? `
                    <button class="view-replies-btn" onclick="toggleReplies(${checkin.id})">
                        <i class="fas fa-comment-dots"></i> 查看回复 (${checkin.reviews})
                    </button>
                    ` : ''}
                </div>
                <div class="reply-input-container" id="replyContainer-${checkin.id}" style="display: none;">
                    <textarea class="reply-input" id="replyInput-${checkin.id}" rows="2" placeholder="写下你的回复..."></textarea>
                    <div class="reply-actions">
                        <button class="cancel-reply-btn" onclick="hideReplyInput(${checkin.id})">取消</button>
                        <button class="reply-btn" onclick="submitReply(${checkin.id})">回复</button>
                    </div>
                </div>
                <div class="child-comments" id="repliesContainer-${checkin.id}" style="display: none;">
                    <div class="loading-replies">加载回复中...</div>
                </div>
            </div>
        `;
            checkinsList.innerHTML += checkinHtml;
        });

        // 处理分页按钮（上一页/下一页）
        renderPagination(hasMore);
    }

    // 渲染分页按钮（上一页/下一页）
    function renderPagination(hasMore) {
        const checkinsList = document.getElementById('checkinsList');

        // 创建分页容器
        const paginationDiv = document.createElement('div');
        paginationDiv.className = 'checkin-pagination';
        paginationDiv.style = `
        display: flex;
        justify-content: center;
        gap: 10px;
        margin: 20px 0;
    `;

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.textContent = '上一页';
        prevBtn.style = `
        padding: 6px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        background: white;
        cursor: pointer;
    `;
        prevBtn.disabled = currentCheckinPage === 1; // 第一页禁用上一页
        prevBtn.onclick = () => {
            if (currentCheckinPage > 1) {
                renderCheckinPage(currentCheckinPage - 1);
            }
        };

        // 页码提示
        const pageInfo = document.createElement('span');
        pageInfo.textContent = `第 ${currentCheckinPage} 页 / 共 ${Math.ceil(totalCheckins / checkinPageSize)} 页`;
        pageInfo.style.color = '#666';

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.textContent = '下一页';
        nextBtn.style = `
        padding: 6px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        background: white;
        cursor: pointer;
    `;
        nextBtn.disabled = !hasMore; // 没有更多时禁用下一页
        nextBtn.onclick = () => {
            if (hasMore) {
                renderCheckinPage(currentCheckinPage + 1);
            }
        };

        // 添加到分页容器
        paginationDiv.appendChild(prevBtn);
        paginationDiv.appendChild(pageInfo);
        paginationDiv.appendChild(nextBtn);
        checkinsList.parentNode.appendChild(paginationDiv);
    }

    function renderComments(reviews) {
        const commentsList = document.getElementById('commentsList');
        commentsList.innerHTML = '';

        reviews.forEach(review => {
            // 主评论HTML结构
            const commentHtml = `
      <div class="comment-item" data-review-id="${review.id}">
        <!-- 主评论内容 -->
        <div class="comment-header">
          <img src="${review.user.avatar}" alt="头像">
          <div>
            <span class="username">${review.user.name}</span>
            <span class="time">${formatTime(review.createTime)}</span>
          </div>
        </div>
        <div class="comment-content">${review.content}</div>

        <!-- 操作按钮：包含“查看回复”按钮 -->
        <div class="comment-actions">
          <button class="like-btn">点赞 (${review.likeCount})</button>
          <button class="reply-btn">回复</button>
          <!-- 查看回复按钮：点击触发显示回复 -->
          <button class="view-replies-btn" onclick="toggleReplies(${review.id})">
            查看回复 (${review.replyCount || 0})
          </button>
        </div>

        <!-- 回复区域：默认隐藏 -->
        <div class="replies-container" id="replies-${review.id}" style="display: none; margin-top: 10px; padding-left: 20px;">
          <!-- 回复内容将通过JS动态加载到这里 -->
          <div class="loading">加载中...</div>
        </div>
      </div>
    `;
            commentsList.innerHTML += commentHtml;
        });
    }
    function fetchRatingData() {
        $.ajax({
            url: "/shop/ratingCount",
            type: "post",
            data: { shopId: currentShopId },
            success: function (res) {
                ratingTotal = res.code === 200 ? (res.data || 0) : 0;
                updateRatingUI();
            },
            error: function () {
                ratingTotal = 0;
                updateRatingUI();
            }
        });

        $.ajax({
            url: "/shop/getRecent100RatingsAverage",
            type: "post",
            data: { shopId: currentShopId },
            success: function (res) {
                const avg = res.code === 200 ? (parseFloat(res.data) || 0) : 0;
                ratingAvg = avg.toFixed(1);
                updateRatingUI();
            },
            error: function () {
                ratingAvg = "0.0";
                updateRatingUI();
            }
        });
    }

    function initCarousel() {
        const carouselList = document.getElementById("carouselList");
        const indicatorsContainer = document.getElementById("carouselIndicators");

        bannerUrls.forEach((url, index) => {
            const img = document.createElement("img");
            img.src = url;
            img.style.width = "100%";
            img.style.height = "100%";
            img.style.objectFit = "cover";
            img.style.flexShrink = "0";
            carouselList.appendChild(img);

            const indicator = document.createElement("span");
            indicator.style.width = "10px";
            indicator.style.height = "10px";
            indicator.style.borderRadius = "50%";
            indicator.style.background = index === 0 ? "#6c5ce7" : "#ddd";
            indicator.style.cursor = "pointer";
            indicator.addEventListener("click", () => goToIndex(index));
            indicatorsContainer.appendChild(indicator);
        });

        document.getElementById("prevBtn").addEventListener("click", showPrev);
        document.getElementById("nextBtn").addEventListener("click", showNext);
        setInterval(showNext, 3000);
    }

    function goToIndex(index) {
        const carouselList = document.getElementById("carouselList");
        const indicators = document.getElementById("carouselIndicators").children;

        currentIndex = index;
        if (currentIndex >= bannerUrls.length) currentIndex = 0;
        if (currentIndex < 0) currentIndex = bannerUrls.length - 1;

        carouselList.style.transform = `translateX(-${currentIndex * 100}%)`;

        for (let i = 0; i < indicators.length; i++) {
            indicators[i].style.background = i === currentIndex ? "#6c5ce7" : "#ddd";
        }
    }

    function showPrev() { goToIndex(currentIndex - 1); }
    function showNext() { goToIndex(currentIndex + 1); }

    function getCurrentTimeStr() {
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        return `${hours}:${minutes}:${seconds}`;
    }

    function isTimeBetween(targetTime, startTime, endTime) {
        const targetSec = timeToSeconds(targetTime);
        const startSec = timeToSeconds(startTime);
        const endSec = timeToSeconds(endTime);

        if (startSec > endSec) {
            return targetSec >= startSec || targetSec <= endSec;
        } else {
            return targetSec >= startSec && targetSec <= endSec;
        }
    }

    function timeToSeconds(timeStr) {
        const [hours, minutes, seconds] = timeStr.split(':').map(Number);
        return hours * 3600 + minutes * 60 + seconds;
    }

    function getLikeStatusAndCount() {
        if (!currentUserId || !currentShopId) return;

        $.ajax({
            url: "/homepage/likeStatus",
            type: "post",
            data: { userId: currentUserId, targetId: currentShopId},
            success: function (res) {
                if (res.code === 200) {
                    updateLikeUI(res.data);
                }
            }
        });

        $.ajax({
            url: "/homepage/likeCount",
            type: "post",
            data: { targetId: currentShopId, target_type: "shop"},
            success: function (res) {
                if (res.code === 200) {
                    document.getElementById('likeCount').textContent = res.data;
                }
            }
        });
    }

    function updateLikeUI(isLiked) {
        const likeButton = document.getElementById('likeButton');
        const likeIcon = likeButton.querySelector('svg');
        const likeText = document.getElementById('likeText');

        if (isLiked === 1) {
            likeIcon.style.color = "#ff4d4f";
            likeText.textContent = "已点赞";
        } else {
            likeIcon.style.color = "#ff7675";
            likeText.textContent = "点赞";
        }
    }

    document.getElementById('likeButton').addEventListener('click', function () {
        if (!currentUserId) {
            alert('请先登录后再点赞～');
            return;
        }
        $.ajax({
            url: "/homepage/likeToggle",
            type: "post",
            data: { userId: currentUserId, targetId: currentShopId,target_type:"shop" },
            success: function (res) {
                if (res.code === 200) {
                    if (res.data==0||res.data==1){
                        alert(res.data==0 ? "取消点赞成功" : "点赞成功");
                        updateLikeUI(res.data);
                    } else {
                        alert("点赞有问题");
                    }
                    $.ajax({
                        url: "/homepage/likeCount",
                        type: "post",
                        data: { targetId: currentShopId , target_type: "shop"},
                        success: function (countRes) {
                            if (countRes.code === 200) {
                                document.getElementById('likeCount').textContent = countRes.data;
                            }
                        }
                    });
                } else {
                    alert('操作失败：' + res.msg);
                }
            }
        });
    });

    function loadFolders(currentUserId) {
        const folderSelect = document.getElementById('folderSelect');
        folderSelect.innerHTML = '<option value="" disabled>加载中...</option>';
        if (!currentUserId) {
            folderSelect.innerHTML = '<option value="0">默认文件夹</option>';
            return;
        }
        $.ajax({
            url: "/personalCollection/selectFavoritesList",
            type: "post",
            data:{ u_id:currentUserId, fatherFolderId:null },
            success: function(res) {
                if (res.code === 200 && res.data && res.data.length > 0) {
                    folderSelect.innerHTML = '';
                    res.data.forEach(folder => {
                        const option = document.createElement('option');
                        option.value = folder.id;
                        option.textContent = folder.folderName;
                        if (folder.isDefault) option.selected = true;
                        folderSelect.appendChild(option);
                    });
                } else {
                    folderSelect.innerHTML = '<option value="default">默认文件夹</option>';
                }
            },
            error: function() {
                folderSelect.innerHTML = '<option value="default">默认文件夹</option>';
                alert('文件夹加载失败，使用默认文件夹');
            }
        })
    }

    function collection(shopId, userId, folderId, reason) {
        if (!shopId || !userId || !folderId) return false;

        $.ajax({
            url: "/personalCollection/collection",
            type: "post",
            data: {
                userId: userId,
                shopId: shopId,
                folderId: parseInt(folderId),
                reason: reason || ""
            },
            success: function (res) {
                if (res.code === 200) {
                    alert('收藏成功！已保存到所选文件夹');
                    closeCollectionDialog();
                    return true;
                } else {
                    alert('收藏失败：' + res.msg);
                    return false;
                }
            },
            error: function (xhr) {
                alert('收藏接口请求失败：' + xhr.responseText);
                return false;
            }
        });
    }

    function showCollectionDialog() {
        if (!currentUserId) {
            alert('请先登录后再收藏～');
            return;
        }
        document.getElementById('collectionDialog').style.display = 'block';
        loadFolders(currentUserId);
    }

    function closeCollectionDialog() {
        document.getElementById('collectionDialog').style.display = 'none';
    }

    function handleConfirmCollection() {
        const folderId = document.getElementById('folderSelect').value;
        const reason = document.getElementById('reasonInput').value.trim();
        collection(currentShopId, currentUserId, folderId, reason);
    }

    function showNewFolderInput() {
        document.getElementById('newFolderInputContainer').style.display = 'flex';
    }

    function hideNewFolderInput() {
        document.getElementById('newFolderInputContainer').style.display = 'none';
        document.getElementById('newFolderName').value = '';
    }

    function createNewFolder() {
        const folderName = document.getElementById('newFolderName').value.trim();
        if (!folderName) {
            alert('请输入文件夹名称');
            return;
        }

        $.ajax({
            url: "/personalCollection/createFolder",
            type: "post",
            data: { u_id: currentUserId, folderName: folderName },
            success: function (res) {
                if (res.code === 200) {
                    alert('文件夹创建成功');
                    hideNewFolderInput();
                    loadFolders(currentUserId);
                } else {
                    alert('创建失败：' + res.msg);
                }
            }
        });
    }

    function checkinUploadImage(file, callback) {
        const formData = new FormData();
        formData.append("file", file);

        $.ajax({
            url: "/upload",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            cache: false,
            success: function (response) {
                if (response.code === 200) {
                    callback(response.data);
                } else {
                    alert("打卡图片上传失败：" + response.msg);
                }
            },
            error: function (xhr) {
                alert("打卡图片上传出错：" + xhr.responseText);
            }
        });
    }

    function checkinSubmitData(context, imgSrc) {
        if (!currentShopId || !currentUserId) {
            alert("请先登录后再提交打卡");
            return;
        }

        const checkinData = {
            shopId: currentShopId,
            userId: currentUserId,
            context: context,
            imgsUrls: imgSrc
        };

        $.ajax({
            url: "/checkings/addCheckin",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(checkinData),
            success: function(res) {
                if (res.code === 200) {
                    alert("打卡成功！");
                    checkId=res.data;
                    document.getElementById('checkinDialog').style.display = 'none';
                    getCheckinsByShopId();
                } else {
                    alert("打卡失败：" + res.msg);
                }
            },
            error: function(res) {
                alert("打卡请求出错：" + res.responseText);
            }
        });
    }

    function updateRatingUI() {
        const ratingInfoEl = document.getElementById("ratingInfo");
        const starsEl = document.getElementById("ratingStars");

        ratingInfoEl.textContent = `${ratingAvg} (${ratingTotal}次评分)`;
        starsEl.innerHTML = "";

        const avg = parseFloat(ratingAvg);
        for (let i = 1; i <= 5; i++) {
            const starSpan = document.createElement("span");
            starSpan.className = "rating-star";
            if (avg >= i) {
                starSpan.textContent = "★";
            } else if (avg >= i - 0.5) {
                starSpan.textContent = "★½";
            } else {
                starSpan.textContent = "☆";
            }
            starsEl.appendChild(starSpan);
        }
    }

    function updateShopStatus() {
        const openTimeStr = document.getElementById('shopOpenTime').value;
        const closeTimeStr = document.getElementById('shopCloseTime').value;
        const currentTimeStr = getCurrentTimeStr();
        const isOpen = isTimeBetween(currentTimeStr, openTimeStr, closeTimeStr);
        const statusElement = document.getElementById('shopStatusText');

        if (isOpen) {
            statusElement.textContent = '营业中';
            statusElement.style.color = '#00b894';
        } else {
            statusElement.textContent = '已超过营业时间';
            statusElement.style.color = '#7f8c8d';
        }
    }

    function formatTime(timeStr) {
        const date = new Date(timeStr);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }

    function showReplyInput(reviewId) {
      const commentItem = document.querySelector(`.checkin-item[data-review-id="${reviewId}"]`);
        if (commentItem) {
            alert("打卡内容不支持回复");
            return;
        }

        if (!currentUserId) {
            alert("请先登录后再回复～");
            return;
        }
        document.getElementById(`replyContainer-${reviewId}`).style.display = 'block';
        document.getElementById(`replyInput-${reviewId}`).focus();
    }

    function hideReplyInput(reviewId) {
        document.getElementById(`replyContainer-${reviewId}`).style.display = 'none';
        document.getElementById(`replyInput-${reviewId}`).value = '';
    }

    function submitReply(reviewId) {
        const commentItem = document.querySelector(`.checkin-item[data-review-id="${reviewId}"]`);
        if (commentItem) {
            alert("打卡内容不支持回复");
            return;
        }

        if (!currentUserId) {
            alert("请先登录后再回复～");
            return;
        }
        const content = document.getElementById(`replyInput-${reviewId}`).value.trim();
        if (!content) {
            alert("回复内容不能为空～");
            return;
        }
        const reviewData = {
            shopId: currentShopId,
            userId: currentUserId,
            parentId:reviewId,
            content: content,
            checkin_id:0
        };
        $.ajax({
            url: "/shop/addReview",
            type: "post",
            contentType: "application/json",
            data: JSON.stringify(reviewData),
            success: function(res) {
                if (res.code === 200) {
                    alert("回复成功～");
                    hideReplyInput(reviewId);
                    loadReplies(reviewId);
                    updateReplyCount(reviewId, 1);
                } else {
                    alert("回复失败：" + res.msg);
                }
            },
            error: function() {
                alert("回复出错，请重试");
            }
        });
    }

    function toggleReplies(reviewId) {
        const container = document.getElementById(`repliesContainer-${reviewId}`);

        if (container.style.display === 'none') {
            // 显示回复区域，并首次加载回复（调用原loadReplies方法）
            container.style.display = 'block';
            // 只有当内容是“加载中”时才加载（避免重复请求）
            if (container.innerHTML.includes('加载中...')) {
                loadReplies(reviewId); // 原loadReplies方法完全不变
            }
        } else {
            // 隐藏回复区域
            container.style.display = 'none';
        }
    }

    function loadReplies(reviewId) {
        const container = document.getElementById(`repliesContainer-${reviewId}`);
        container.innerHTML = '<div class="loading-replies">加载中...</div>';

        $.ajax({
            url: "/shop/getReplies",
            type: "post",
            data: { reviewId: reviewId },
            success: function(res) {
                if (res.code === 200) {
                    const replies = res.data || [];

                    if (replies.length === 0) {
                        // 暂无回复：使用与回复框一致的样式（不换行，嵌入当前区域）
                        container.innerHTML = `
            <div class="no-replies" style="
              font-size: 14px;
              color: #999;
              padding: 8px 0;
              margin: 0;  /* 去除默认外边距，避免换行 */
            ">
              暂无回复
            </div>
          `;
                        return;
                    }

                    // 有回复时，渲染回复列表（样式与回复框统一）
                    let repliesHtml = '';
                    replies.forEach(reply => {
                        repliesHtml += `
            <div class="reply-item" style="
              padding: 8px 0;
              border-bottom: 1px dashed #eee;
              font-size: 14px;  /* 与回复框字体大小一致 */
            ">
              <div class="reply-header" style="margin-bottom: 4px; font-size: 13px;">
                <span class="reply-author" style="font-weight: 600;">${reply.user?.username || '匿名用户'}</span>
                <span class="reply-time" style="color: #999;">${formatTime(reply.createdAt)}</span>
              </div>
              <div class="reply-content" style="color: #4a4a4a; margin-bottom: 4px;">
                ${reply.content}
              </div>
              <div class="reply-actions" style="font-size: 12px;">
                <button onclick="likeReply(${reply.id}, ${reviewId})" style="
                  background: none;
                  border: none;
                  color: #666;
                  cursor: pointer;
                ">
                  ${likedCommentIds.has(reply.id) ? '❤️' : '♡'} ${reply.likeCount || 0}
                </button>
              </div>
            </div>
          `;
                    });
                    container.innerHTML = repliesHtml;
                } else {
                    // 加载失败也保持统一样式
                    container.innerHTML = `
          <div class="no-replies" style="
            font-size: 14px;
            color: #999;
            padding: 8px 0;
            margin: 0;
          ">
            加载回复失败
          </div>
        `;
                }
            },
            error: function() {
                container.innerHTML = `
        <div class="no-replies" style="
          font-size: 14px;
          color: #999;
          padding: 8px 0;
          margin: 0;
        ">
          加载回复失败
        </div>
      `;
            }
        });
    }

    function previewImage(imgUrl) {
        const preview = document.createElement('div');
        preview.style.cssText = `
            position: fixed; top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.9); z-index: 9999;
            display: flex; align-items: center; justify-content: center;
        `;
        preview.innerHTML = `<img src="${imgUrl}" style="max-width: 90%; max-height: 90%; object-fit: contain;">`;
        preview.onclick = () => preview.remove();
        document.body.appendChild(preview);
    }

    function updateReplyCount(reviewId, change) {
        const viewBtn = document.querySelector(`.comment-item[data-review-id="${reviewId}"] .view-replies-btn`);
        if (viewBtn) {
            // 提取当前回复数（兼容“查看回复”和“查看回复 (N)”两种文本）
            const match = viewBtn.textContent.match(/\d+/);
            const currentCount = match ? parseInt(match[0]) : 0;
            viewBtn.innerHTML = `<i class="fas fa-comment-dots"></i> 查看回复 (${currentCount + change})`;
        }
    }
    function showAddCommentDialog() {
        const dialog = document.createElement('div');
        dialog.id = 'addCommentDialog';
        dialog.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 9999;
            display: flex;
            align-items: flex-end;
        `;

        dialog.innerHTML = `
            <div style="width: 100%; background: white; border-radius: 16px 16px 0 0; padding: 20px;">
                <h3 style="margin-top: 0; margin-bottom: 15px; font-size: 18px;">发表评论</h3>
                <textarea id="newCommentContent" rows="5"
                    style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px; resize: none;"
                    placeholder="分享你的体验..."></textarea>
                <div style="margin: 15px 0;">
                    <label style="display: block; margin-bottom: 8px;">上传图片（可选，最多1张）</label>
                    <input type="file" id="commentFileInput" accept="image/*" style="display: none;">
                    <button id="selectCommentImagesBtn" style="padding: 6px 12px; background: #eee; border: none; border-radius: 4px; cursor: pointer;">
                        选择图片
                    </button>
                    <div id="commentImagePreviewContainer" style="margin-top: 10px; display: none; position: relative; width: 120px; height: 120px;">
                        <img id="commentImagePreview" src="" style="width: 100%; height: 100%; object-fit: cover; border-radius: 8px;">
                        <div class="uploading-mask" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.3); color: white; display: flex; align-items: center; justify-content: center; font-size: 12px;">
                            上传中...
                        </div>
                        <button id="removeCommentImageBtn" style="position: absolute; top: -5px; right: -5px; background: #ff4d4f; color: white; border: none; border-radius: 50%; width: 24px; height: 24px; cursor: pointer; font-size: 14px; display: none;">×</button>
                    </div>
                </div>
                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                    <button id="cancelCommentBtn" style="padding: 10px 20px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;">取消</button>
                    <button id="submitCommentBtn" style="padding: 10px 20px; background: #6c5ce7; color: white; border: none; border-radius: 4px; cursor: pointer;">发布评论</button>
                </div>
            </div>
        `;
        document.body.appendChild(dialog);

        let commentImageUrl = null;
        let isUploading = false;

        document.getElementById('selectCommentImagesBtn').addEventListener('click', () => {
            const fileInput = document.getElementById('commentFileInput');
            fileInput.value = '';
            fileInput.click();
        });

        document.getElementById('commentFileInput').addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;

            if (!file.type.startsWith('image/')) {
                alert('请选择图片文件');
                return;
            }

            const previewContainer = document.getElementById('commentImagePreviewContainer');
            const previewImg = document.getElementById('commentImagePreview');
            const uploadingMask = previewContainer.querySelector('.uploading-mask');
            const removeBtn = document.getElementById('removeCommentImageBtn');

            previewContainer.style.display = 'block';
            uploadingMask.style.display = 'flex';
            removeBtn.style.display = 'none';
            isUploading = true;

            const reader = new FileReader();
            reader.onload = (event) => {
                previewImg.src = event.target.result;
                const formData = new FormData();
                formData.append('file', file);
                $.ajax({
                    url: '/upload',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: (res) => {
                        if (res.code === 200) {
                            commentImageUrl = res.data;
                            uploadingMask.style.display = 'none';
                            removeBtn.style.display = 'block';
                        } else {
                            alert(`图片上传失败：${res.msg}`);
                            previewContainer.style.display = 'none';
                        }
                    },
                    error: () => {
                        alert('图片上传接口出错');
                        previewContainer.style.display = 'none';
                    },
                    complete: () => {
                        isUploading = false;
                    }
                });
            };
            reader.readAsDataURL(file);
        });

        document.getElementById('removeCommentImageBtn').addEventListener('click', () => {
            commentImageUrl = null;
            document.getElementById('commentImagePreviewContainer').style.display = 'none';
            document.getElementById('commentFileInput').value = '';
        });

        document.getElementById('cancelCommentBtn').addEventListener('click', () => {
            dialog.remove();
        });

        dialog.addEventListener('click', (e) => {
            if (e.target === dialog) dialog.remove();
        });

        document.getElementById('submitCommentBtn').addEventListener('click', () => {
            const content = document.getElementById('newCommentContent').value.trim();
            if (!content) {
                alert('评论内容不能为空～');
                return;
            }

            if (isUploading) {
                alert('图片正在上传，请稍候...');
                return;
            }

            const reviewData = {
                shopId: currentShopId,
                userId: currentUserId,
                parentId: null,
                content: content,
                imageUrls: commentImageUrl,
                checkin_id: 0
            };

            $.ajax({
                url: '/shop/addReview',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(reviewData),
                success: (res) => {
                    if (res.code === 200) {
                        alert('评论发表成功～');
                        dialog.remove();
                        currentCommentPage = 1; // 重置页码
                        hasMoreComments = true; // 重置是否有更多数据
                        getReviewsByShopId(currentCommentPage, commentPageSize, false); // 明确传递参数
                    } else {
                        alert(`评论失败：${res.msg}`);
                    }
                },
                error: () => {
                    alert('评论提交接口出错');
                }
            });
        });
    }

    const getCheckinImgSrc = handleImageUpload(
        'checkinFileInput',
        'checkinImagePreviewContainer',
        'checkinRemoveImageBtn',
        function(imgSrc) {
            checkinImgSrc = imgSrc;
        }
    );

    function handleImageUpload(fileInputId, previewContainerId, removeBtnId, callback) {
        let checkinImgSrc = "";

        document.getElementById(fileInputId).addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const previewContainer = document.getElementById(previewContainerId);
                const previewImg = document.getElementById(previewContainerId.replace('Container', 'Preview'));
                const reader = new FileReader();
                reader.onload = function(event) {
                    previewImg.src = event.target.result;
                    previewContainer.style.display = 'flex';
                };
                reader.readAsDataURL(file);

                const formData = new FormData();
                formData.append("file", file);
                $.ajax({
                    url: "/upload",
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    cache: false,
                    success: function (response) {
                        if (response.code === 200) {
                            checkinImgSrc = response.data;
                            callback(checkinImgSrc);
                        } else {
                            alert("图片上传失败：" + response.msg);
                        }
                    },
                    error: function (xhr) {
                        alert("图片上传出错：" + xhr.responseText);
                    }
                });
            }
        });

        document.getElementById(removeBtnId).addEventListener('click', function() {
            document.getElementById(previewContainerId).style.display = 'none';
            document.getElementById(fileInputId).value = '';
            checkinImgSrc = "";
        });

        return function() {
            return checkinImgSrc;
        };
    }
    function likeComment(commentId) {
        if (!currentUserId) {
            alert("请先登录后再点赞～");
            return;
        }

        $.ajax({
            url: "/shop/likeReview",
            type: "post",
            data: {
                targetId: commentId,
                userId: currentUserId,
                target_type:"shopReview"
            },
            success: function(res) {
                if (res.code === 200) {
                    let data=res.data;
                    if (data==0){
                        alert("取消点赞成功！")
                    } else if (data==1){
                        alert("点赞成功！")
                    }else{
                        alert("获取信息失败！")
                    }
                    $.ajax({
                        url: "/homepage/likeCount",
                        type: "post",
                        data: {
                            targetId: commentId,
                            target_type:"shopReview"
                        },
                        success: function(countRes) {
                            if (countRes.code === 200) {
                                const count = countRes.data;
                                const likeBtn = document.querySelector(`[data-review-id="${commentId}"] .like-btn`);

                                if (likeBtn) {
                                    // 更新点赞数
                                    likeBtn.innerHTML = likeBtn.innerHTML.replace(/\d+/, count);

                                    // 更新高亮状态
                                    if (data === 1) {
                                        likeBtn.classList.add('liked');
                                        likeBtn.innerHTML = likeBtn.innerHTML.replace('♡', '❤️');
                                    } else if (data === 0) {
                                        likeBtn.classList.remove('liked');
                                        likeBtn.innerHTML = likeBtn.innerHTML.replace('❤️', '♡');
                                    }
                                }
                            } else {
                                alert(countRes.msg || "获取点赞数失败");
                            }
                        },
                        error: function() {
                            alert("查询点赞数出错");
                        }
                    });
                } else {
                    alert(res.msg || "操作失败");
                }
            },
            error: function() {
                alert("点赞操作出错");
            }
        });
    }

</script>
</body>
</html>